package framework.service.client;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.SAXException;

import framework.Message;
import framework.Service;
import framework.service.cluster.Dispatcher;
import framework.utils.http.Http;
import framework.utils.http.HttpConn;
import framework.utils.http.HttpRequest;

/**
 * Contains client request.<br>
 *
 * @author	Orlin Tomov
 * @version	0.2
 */
public class ClientRequest extends HttpConn implements Message {

	private HttpRequest request = new HttpRequest();
	public List<Object> lines = new ArrayList<Object>();

	/**
	  * Creates ClientReques by client Socket
	  * @param	socket	of the client
	  * @throws	IOException
	  * @throws	SAXException
	  */
	public ClientRequest(Service service, Socket socket) throws IOException, SAXException {
		super(service, socket);
	}

	/**
	 * Creates ClientRequest by host and port
	 * @param	dispatcher	service of the owner
	 * @param	host	of the client
	 * @param	port	of the client
	 * @throws IOException 
	 */
	public ClientRequest(Dispatcher dispatcher, String host, int port) throws IOException {
		super(dispatcher, host, port);
	}

	/**
	 * Extract client request.
	 */
	public void request() {
		try {
			this.lines = request.parse(in, lines);
		} catch (SAXException e) {
		} catch (IOException e) {
		}
	}

	/**
	 * Sets infinite connection.
	 */
	public void setInfinite() {
		try {
			socket.setSoTimeout(0);
			socket.setKeepAlive(true);
		} catch (SocketException e) {
		}
	}

	/**
	 * Extract single line from client request contains the value
	 * @param	value
	 * @return	request line
	 */
	public String getLine(String value) {
		return request.getLine(value);  
	}

	/**
	 * Extract from client request user value
	 * @return	user value;
	 */
	public String getUser() {
		return request.getUser();
	}

	/**
	 * @return client port
	 */
	public String getClientPort() {
		return ((String)lines.get(0)).substring(((String)lines.get(0)).indexOf(":") + 1);
	}

	/**
	 * @return	kind of compression
	 */
	public int getCompression() {
		for (int i = 0; i < lines.size(); i++) {
			if (lines.get(i) instanceof String) {
				if (((String)lines.get(i)).equals(Http.ACCEPT_ENC_GZIP)) {
					return Http.GZIP;
				}
				if (((String)lines.get(i)).equals(Http.ACCEPT_ENC_ZLIB)) {
					return Http.ZLIB;
				}
			}
		}
		return Http.NO;
	}
}
